class MVVM {
  constructor(el, data) {
    this.el = document.querySelector(el)
    this._data = data
    // this.data = data
    this.domPool = []
    this.init()
  }
  init() {
    this.initData()
    this.bindDom(this.el)
    this.bindInput(this.el)
    console.log(this.domPool)
  }
  bindDom(el) {
    const childNodes = el.childNodes
    childNodes.forEach(item => {
      if (item.nodeType === 3) {
        const value = item.nodeValue
        if (value.trim().length) {
          const _isVaild = /\{\{(.+?)\}\}/.test(value)
          if (_isVaild) {
            const _key = value.match(/\{\{(.+?)\}\}/)[1].trim()
            this.domPool[_key] = item.parentNode
            item.parentNode.innerHTML = this.data[_key] || undefined
          }
        }
      }

      item.childNodes && this.bindDom(item)
    })
  }
  initData() {
    const _this = this
    this.data = {}
    for (const key in this._data) {
      Object.defineProperty(this.data, key, {
        get() {
          return _this._data[key]
        },
        set(newValue) {
          console.log('=================')
          _this.domPool[key].innerText = newValue
          _this._data[key] = newValue
        }
      })
    }
    /* this.data = new Proxy(this.data, {
      get(target, key) {
        return Reflect.get(target, key)
      },
      set(target, key, value) {
        _this.domPool[key].innerText = value
        return Reflect.set(target, key, value)
      }
    })*/
  }
  bindInput(el) {
    const allInput = el.querySelectorAll('input')
    allInput.forEach(input => {
      const vModel = input.getAttribute('v-model')
      if (vModel) {
        input.addEventListener('keyup', this.handelInput.bind(this, vModel, input), false)
      }
    })
  }
  handelInput(key, input) {
    const _value = input.value
    this.data[key] = _value
  }
  setData(key, value) {
    this.data[key] = value
  }
}
